const { 
  Connection, 
  Keypair, 
  PublicKey, 
  Transaction,
  sendAndConfirmTransaction,
  LAMPORTS_PER_SOL 
} = require('@solana/web3.js');
const {
  getAssociatedTokenAddress,
  createAssociatedTokenAccountInstruction,
  createTransferInstruction,
  getAccount,
  TOKEN_PROGRAM_ID,
  ASSOCIATED_TOKEN_PROGRAM_ID
} = require('@solana/spl-token');
const fs = require('fs');

// 配置
const DEVNET_RPC = 'https://api.devnet.solana.com';
const TOKEN_MINT = '7uTpUhobocigTVnxF7Z8w5iGgEnxqn9gCm5Bazk5mW8i';
const SELLER_ADDRESS = 'shTdKtBScJMC4GkKmasiE9iMKrtZnMFUtwVTdSXsKac';

// 买家地址（从命令行参数或使用默认）
const BUYER_ADDRESS = process.argv[2] || '3N5UkPsssdMAjjyF5vje7k5pgJoYPsBouPBLbtZaxa2U';

// 更多样化的交易模式
const TRADING_PATTERNS = [
  { type: 'small_buy', solAmount: 0.05, tokenAmount: 500, description: '小额买入' },
  { type: 'medium_buy', solAmount: 0.15, tokenAmount: 1500, description: '中等买入' },
  { type: 'large_buy', solAmount: 0.25, tokenAmount: 2500, description: '大额买入' },
  { type: 'quick_flip', solAmount: 0.08, tokenAmount: 800, description: '快速交易' },
  { type: 'accumulation', solAmount: 0.12, tokenAmount: 1200, description: '逢低吸纳' },
  { type: 'fomo_buy', solAmount: 0.3, tokenAmount: 3000, description: 'FOMO买入' },
  { type: 'dip_buy', solAmount: 0.06, tokenAmount: 600, description: '抄底买入' },
  { type: 'momentum_buy', solAmount: 0.18, tokenAmount: 1800, description: '动量买入' },
];

async function createAdvancedTokenPurchase() {
  console.log('🎯 高级代币交易模拟器启动...\n');
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  const tokenMint = new PublicKey(TOKEN_MINT);
  const seller = new PublicKey(SELLER_ADDRESS);
  const buyer = new PublicKey(BUYER_ADDRESS);
  
  console.log(`📊 交易配置:`);
  console.log(`- 代币: ${TOKEN_MINT}`);
  console.log(`- 卖家: ${SELLER_ADDRESS}`);
  console.log(`- 买家: ${BUYER_ADDRESS}`);
  console.log(`- RPC: ${DEVNET_RPC}\n`);
  
  // 获取账户余额
  try {
    const buyerBalance = await connection.getBalance(buyer);
    const sellerBalance = await connection.getBalance(seller);
    
    console.log(`💰 当前余额:`);
    console.log(`- 买家: ${(buyerBalance / LAMPORTS_PER_SOL).toFixed(4)} SOL`);
    console.log(`- 卖家: ${(sellerBalance / LAMPORTS_PER_SOL).toFixed(4)} SOL\n`);
  } catch (error) {
    console.log('⚠️  无法获取余额信息\n');
  }
  
  // 获取代币账户信息
  const sellerTokenAccount = await getAssociatedTokenAddress(tokenMint, seller);
  const buyerTokenAccount = await getAssociatedTokenAddress(tokenMint, buyer);
  
  console.log(`🏦 代币账户:`);
  console.log(`- 卖家代币账户: ${sellerTokenAccount.toString()}`);
  console.log(`- 买家代币账户: ${buyerTokenAccount.toString()}\n`);
  
  // 检查代币账户余额
  try {
    const sellerTokenBalance = await getAccount(connection, sellerTokenAccount);
    console.log(`💎 卖家代币余额: ${sellerTokenBalance.amount.toString()}`);
  } catch (error) {
    console.log('❌ 无法获取卖家代币余额');
  }
  
  try {
    const buyerTokenBalance = await getAccount(connection, buyerTokenAccount);
    console.log(`💎 买家代币余额: ${buyerTokenBalance.amount.toString()}`);
  } catch (error) {
    console.log('💎 买家代币余额: 0 (账户不存在)');
  }
  
  console.log('\n🔥 开始执行交易序列...\n');
  
  const executedTrades = [];
  let totalVolume = 0;
  let totalTokens = 0;
  
  // 随机选择交易模式并执行
  for (let i = 0; i < 8; i++) {
    const pattern = TRADING_PATTERNS[Math.floor(Math.random() * TRADING_PATTERNS.length)];
    const tradeId = `TRADE_${Date.now()}_${i}`;
    
    console.log(`📈 交易 ${i + 1}/8: ${pattern.description}`);
    console.log(`   类型: ${pattern.type}`);
    console.log(`   数量: ${pattern.tokenAmount} 代币`);
    console.log(`   价格: ${pattern.solAmount} SOL`);
    console.log(`   ID: ${tradeId}`);
    
    try {
      // 创建交易
      const transaction = new Transaction();
      
      // 如果是第一次交易且买家账户不存在，创建代币账户
      if (i === 0) {
        try {
          await getAccount(connection, buyerTokenAccount);
        } catch (error) {
          console.log('   📝 创建买家代币账户...');
          transaction.add(
            createAssociatedTokenAccountInstruction(
              buyer,
              buyerTokenAccount,
              buyer,
              tokenMint
            )
          );
        }
      }
      
      // 添加代币转账指令
      const tokenAmountWithDecimals = pattern.tokenAmount * Math.pow(10, 9);
      transaction.add(
        createTransferInstruction(
          sellerTokenAccount,
          buyerTokenAccount,
          seller, // 需要卖家签署
          tokenAmountWithDecimals
        )
      );
      
      // 添加SOL支付指令
      const { SystemProgram } = require('@solana/web3.js');
      transaction.add(
        SystemProgram.transfer({
          fromPubkey: buyer,
          toPubkey: seller,
          lamports: pattern.solAmount * LAMPORTS_PER_SOL
        })
      );
      
      // 设置交易参数
      const { blockhash } = await connection.getLatestBlockhash();
      transaction.recentBlockhash = blockhash;
      transaction.feePayer = buyer;
      
      // 模拟交易费用计算
      const estimatedFee = 5000; // 约0.000005 SOL
      
      // 记录交易详情
      const tradeDetails = {
        id: tradeId,
        timestamp: new Date().toISOString(),
        type: pattern.type,
        description: pattern.description,
        tokenAmount: pattern.tokenAmount,
        solAmount: pattern.solAmount,
        pricePerToken: pattern.solAmount / pattern.tokenAmount,
        estimatedFee: estimatedFee / LAMPORTS_PER_SOL,
        status: 'prepared',
        transactionSize: transaction.serialize({ requireAllSignatures: false }).length
      };
      
      console.log(`   ✅ 交易已准备 (${tradeDetails.transactionSize} bytes)`);
      console.log(`   💰 单价: ${tradeDetails.pricePerToken.toFixed(8)} SOL/代币`);
      console.log(`   ⛽ 预计费用: ${tradeDetails.estimatedFee.toFixed(6)} SOL`);
      
      executedTrades.push(tradeDetails);
      totalVolume += pattern.solAmount;
      totalTokens += pattern.tokenAmount;
      
      // 模拟确认时间
      const confirmationTime = Math.random() * 2000 + 1000; // 1-3秒
      console.log(`   ⏳ 模拟确认中... (${(confirmationTime/1000).toFixed(1)}s)`);
      await new Promise(resolve => setTimeout(resolve, confirmationTime));
      
      console.log(`   🎉 交易模拟成功!\n`);
      
    } catch (error) {
      console.error(`   ❌ 交易失败: ${error.message}\n`);
    }
    
    // 交易间隔
    if (i < 7) {
      const interval = Math.random() * 3000 + 2000; // 2-5秒间隔
      console.log(`   ⏸️  等待 ${(interval/1000).toFixed(1)}s 后执行下一个交易...\n`);
      await new Promise(resolve => setTimeout(resolve, interval));
    }
  }
  
  // 生成交易报告
  console.log('📊 === 交易完成报告 ===\n');
  
  const avgPrice = totalVolume / totalTokens;
  const totalFees = executedTrades.reduce((sum, trade) => sum + trade.estimatedFee, 0);
  
  console.log(`📈 交易统计:`);
  console.log(`- 完成交易: ${executedTrades.length}/8`);
  console.log(`- 总交易量: ${totalVolume.toFixed(4)} SOL`);
  console.log(`- 总代币数: ${totalTokens.toLocaleString()}`);
  console.log(`- 平均价格: ${avgPrice.toFixed(8)} SOL/代币`);
  console.log(`- 总手续费: ${totalFees.toFixed(6)} SOL`);
  console.log(`- 交易密度: ${(executedTrades.length / 8 * 100).toFixed(1)}%\n`);
  
  // 按交易类型分组统计
  const typeStats = {};
  executedTrades.forEach(trade => {
    if (!typeStats[trade.type]) {
      typeStats[trade.type] = { count: 0, volume: 0, tokens: 0 };
    }
    typeStats[trade.type].count++;
    typeStats[trade.type].volume += trade.solAmount;
    typeStats[trade.type].tokens += trade.tokenAmount;
  });
  
  console.log(`📋 按类型统计:`);
  Object.entries(typeStats).forEach(([type, stats]) => {
    console.log(`- ${type}: ${stats.count}次, ${stats.volume.toFixed(3)} SOL, ${stats.tokens} 代币`);
  });
  
  // 保存交易记录
  const reportData = {
    summary: {
      timestamp: new Date().toISOString(),
      totalTrades: executedTrades.length,
      totalVolume,
      totalTokens,
      averagePrice: avgPrice,
      totalFees,
      tokenMint: TOKEN_MINT,
      seller: SELLER_ADDRESS,
      buyer: BUYER_ADDRESS
    },
    trades: executedTrades,
    typeStats
  };
  
  try {
    fs.writeFileSync(
      'trading-report.json', 
      JSON.stringify(reportData, null, 2)
    );
    console.log('\n💾 交易报告已保存到 trading-report.json');
  } catch (error) {
    console.log('\n⚠️  无法保存交易报告');
  }
  
  console.log('\n🎯 交易模拟完成！');
  console.log('\n💡 提示:');
  console.log('- 这是交易结构模拟，未实际执行链上交易');
  console.log('- 要执行真实交易，需要私钥和充足的SOL余额');
  console.log('- 建议在测试网环境中进行真实交易测试');
  
  return reportData;
}

// 创建快速交易函数
async function quickTrade(solAmount = 0.1, tokenAmount = 1000) {
  console.log(`🚀 快速交易: ${tokenAmount} 代币 ← ${solAmount} SOL\n`);
  
  const connection = new Connection(DEVNET_RPC, 'confirmed');
  const tokenMint = new PublicKey(TOKEN_MINT);
  const seller = new PublicKey(SELLER_ADDRESS);
  const buyer = new PublicKey(BUYER_ADDRESS);
  
  try {
    const transaction = new Transaction();
    
    const sellerTokenAccount = await getAssociatedTokenAddress(tokenMint, seller);
    const buyerTokenAccount = await getAssociatedTokenAddress(tokenMint, buyer);
    
    // 检查买家代币账户
    try {
      await getAccount(connection, buyerTokenAccount);
    } catch (error) {
      transaction.add(
        createAssociatedTokenAccountInstruction(
          buyer,
          buyerTokenAccount,
          buyer,
          tokenMint
        )
      );
    }
    
    // 代币转账
    transaction.add(
      createTransferInstruction(
        sellerTokenAccount,
        buyerTokenAccount,
        seller,
        tokenAmount * Math.pow(10, 9)
      )
    );
    
    // SOL支付
    const { SystemProgram } = require('@solana/web3.js');
    transaction.add(
      SystemProgram.transfer({
        fromPubkey: buyer,
        toPubkey: seller,
        lamports: solAmount * LAMPORTS_PER_SOL
      })
    );
    
    const { blockhash } = await connection.getLatestBlockhash();
    transaction.recentBlockhash = blockhash;
    transaction.feePayer = buyer;
    
    const serialized = transaction.serialize({ requireAllSignatures: false });
    
    console.log('✅ 快速交易准备完成');
    console.log(`📋 交易大小: ${serialized.length} bytes`);
    console.log(`💰 单价: ${(solAmount / tokenAmount).toFixed(8)} SOL/代币`);
    
    return {
      success: true,
      transaction: serialized.toString('base64'),
      details: { solAmount, tokenAmount, price: solAmount / tokenAmount }
    };
    
  } catch (error) {
    console.error('❌ 快速交易失败:', error.message);
    return { success: false, error: error.message };
  }
}

// 主函数
if (require.main === module) {
  const command = process.argv[3] || 'advanced';
  
  if (command === 'quick') {
    const solAmount = parseFloat(process.argv[4]) || 0.1;
    const tokenAmount = parseInt(process.argv[5]) || 1000;
    quickTrade(solAmount, tokenAmount);
  } else {
    createAdvancedTokenPurchase();
  }
}

module.exports = { 
  createAdvancedTokenPurchase,
  quickTrade
};
